<template>
	<view>
		<view class="login-content">
			<!-- 排号和列号输入框 -->
			<view class="input-group">
				<view class="input-item">
					<text>排号：</text>
					<input 
						v-model="rowId" 
						type="number" 
						placeholder="请输入排号"
						@input="onInputChange"
						:disabled="isLoading"
						style="background: #F8F8F8; height: 80rpx; padding: 0 20rpx; border-radius: 10rpx;"
					/>
				</view>
				<view class="input-item">
					<text>列号：</text>
					<input 
						v-model="houseId" 
						type="number" 
						placeholder="请输入鸽舍号"
						@input="onInputChange"
						:disabled="isLoading"
						style="background: #F8F8F8; height: 80rpx; padding: 0 20rpx; border-radius: 10rpx;"
					/>
				</view>
			</view>

			<!-- 输入提示 -->
			<view v-if="showInputTip" class="tip-message">
				请输入排号和鸽舍号
			</view>

			<!-- 重复卡片信息 -->
			<view class="info-section">
				<view class="houseId row-center" :class="{ 'has-repeat': repeatHouseId }">
					{{ repeatHouseId ? '重复卡片位于鸽舍号:' + repeatHouseId : '无重复卡片' }}
				</view>
				<view class="uni-nav-bar" v-if="repeatHouseId">
					<span>|</span> 
					<br>重复卡片位于<br>  
					<span>|</span>
				</view>
			</view>

			<!-- NFC读取状态 -->
			<view class="nfc-section">
				<view class="houseId row-center" :class="{ 'nfc-read': addNfcId, 'nfc-waiting': !addNfcId }">
					{{ addNfcId ? '已读取的卡号:' + addNfcId : '请靠近NFC卡片读取卡号' }}
				</view>
				<view v-if="isLoading" class="loading-text">
					正在处理中...
				</view>
			</view>

			<!-- 添加结果 -->
			<view class="result-section">
				<view class="uni-nav-bar" v-if="show_addhouseid">
					<span>|</span> 
					<br>已添加至<br>  
					<span>|</span>
				</view>
				<view class="houseId row-center success-result" v-if="show_addhouseid">
					鸽舍号 {{ show_addhouseid }}
				</view>
			</view>

			<!-- 顶部提示 -->
			<u-toast ref="uToast" />
		</view>
	</view>	
</template>

<script>
	import {
		mapGetters,
		mapActions
	} from 'vuex'
	import { reqAddHouse } from '@/api/index.js'
	
	export default {
		data() {
			  return {
			        repeatHouseId: '',
			        show_addhouseid: '',
			        successMessage: '',
			        showClearIcon: false,
			        chooseSiteId: 1,
			        rowId: '', // 添加排号
			        houseId: '', // 添加列号（鸽舍号）
			        isLoading: false,
			        showInputTip: false
			    
			}
		},
		computed: {
			...mapGetters(['show_nfcId', 'addNfcId', 'operationSiteId']),
			nfcId() {
				return this.addNfcId;
			},
			isFormValid() {
				return this.rowId && this.houseId && this.nfcId;
			},
			// 获取当前仓号
			currentSiteId() {
				return this.operationSiteId || uni.getStorageSync('siteId') || 1;
			}
		},
		watch: {
			nfcId(newvalue, oldvalue) {
				if (!newvalue) return;
				
				this.repeatHouseId = '';
				this.show_addhouseid = '';
				this.showInputTip = false;
				
				if (this.rowId && this.houseId) {
					// 自动触发添加
					this.houseAdd();
				} else {
					// 温和提示用户输入
					this.showInputTip = true;
					this.$nextTick(() => {
						setTimeout(() => {
							this.showInputTip = false;
						}, 3000);
					});
				}
			},
			rowId(newVal) {
				this.showInputTip = false;
				this.clearResults();
			},
			houseId(newVal) {
				this.showInputTip = false;
				this.clearResults();
			}
		},
		methods: {
			onInputChange() {
				this.clearResults();
				this.showInputTip = false;
			},
			
			clearResults() {
				this.repeatHouseId = '';
				this.show_addhouseid = '';
			},
			
			// 简单的格式化函数，直接使用当前仓号
			formatHouseId(houseId, siteId) {
				// 直接使用传入的仓号，格式化为：仓号-排号-列号
				return `${siteId}-${this.rowId}-${this.houseId}`;
			},
			
			async houseAdd() {
			    if (!this.rowId || !this.houseId) {
			        uni.showToast({
			            title: '请先输入排号和鸽舍号',
			            icon: 'none',
			            duration: 2000
			        });
			        return;
			    }
			    
			    if (!this.nfcId) {
			        uni.showToast({
			            title: '请先读取NFC卡片',
			            icon: 'none',
			            duration: 2000
			        });
			        return;
			    }
			    
			    console.log("nfcId:", this.nfcId, "排号:", this.rowId, "鸽舍号:", this.houseId);
			    
			    this.isLoading = true;
			    this.clearResults();
			    
			    const obj = {
			        site_id: this.currentSiteId, // 使用当前仓号
			        row_id: this.rowId,
			        houseid: this.houseId,
			        nfcid: this.nfcId
			    };
			    
			    try {
			        const data = await reqAddHouse(obj);
			        if (data.code === 200) {
			            this.$refs.uToast.show({
			                title: data.msg,
			                type: 'success',
			                duration: 1500
			            });
			            
			            // 关键：使用后端返回的数据格式化鸽舍号
			            if (data.house) {
			                this.show_addhouseid = this.formatHouseId(data.house.house_id, this.currentSiteId);
			            } else if (data.newHouse) {
			                // 兼容原始版本的返回格式
			                this.show_addhouseid = this.formatHouseId(data.newHouse.house_id, this.currentSiteId);
			            }
			            
			        } else {
			            this.$refs.uToast.show({
			                title: data.msg,
			                type: 'error',
			                duration: 2000
			            });
			        }
			    } catch (error) {
			        this.handleError(error);
			    } finally {
			        this.isLoading = false;
			    }
			},
			
			handleError(error) {
				if (error.response) {
					const responseData = error.response.data;
					const statusCode = error.response.data.code;
					console.log('Error status code:', statusCode);
					console.log('Response data:', responseData);
					
					if (statusCode == 400) {
						// 对于重复卡片，我们也使用当前仓号来显示
						this.repeatHouseId = this.formatHouseId(responseData.houseId, this.currentSiteId);
						this.$refs.uToast.show({
							title: responseData.msg || '该卡片已被使用',
							type: 'warning',
							duration: 2500
						});
					} else if (statusCode == 404) {
						this.$refs.uToast.show({
							title: '未找到对应的鸽舍记录',
							type: 'error',
							duration: 2000
						});
					} else {
						this.$refs.uToast.show({
							title: responseData.msg || '请求失败',
							type: 'error',
							duration: 2000
						});
					}
				} else {
					this.$refs.uToast.show({
						title: '网络连接失败，请检查网络',
						type: 'error',
						duration: 2000
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.login-content {
		padding: 30rpx;
	}
	
	.input-group {
		padding: 20rpx 0;
		display: flex;
		flex-direction: column;
		gap: 30rpx;
	}
	
	.input-item {
		display: flex;
		align-items: center;
		gap: 20rpx;
		font-size: 32rpx;
	}
	
	.tip-message {
		text-align: center;
		color: #ff6b35;
		font-size: 28rpx;
		margin: 20rpx 0;
		padding: 20rpx;
		background: #fff8f6;
		border-radius: 10rpx;
		border: 1rpx solid #ff6b35;
	}
	
	.info-section, .nfc-section, .result-section {
		margin: 40rpx 0;
	}
	
	.houseId {
		width: 100%;
		margin: 10rpx auto;
		padding: 25rpx;
		font-size: 32rpx;
		border-radius: 15rpx;
		color: #fff;
		text-align: center;
		transition: all 0.3s ease;
	}
	
	/* 默认状态 */
	.houseId {
		background-color: #7d9ad2;
	}
	
	/* 重复卡片样式 */
	.has-repeat {
		background-color: #ff4757 !important;
	}
	
	/* NFC读取状态样式 */
	.nfc-read {
		background-color: #ff7c10 !important;
	}
	
	.nfc-waiting {
		background-color: #a4b0be !important;
	}
	
	/* 成功结果样式 */
	.success-result {
		background-color: #2ed573 !important;
		font-weight: bold;
	}
	
	.loading-text {
		text-align: center;
		color: #3498db;
		font-size: 28rpx;
		margin-top: 20rpx;
	}
	
	.uni-nav-bar {
		text-align: center;
		color: #7d9ad2;
		font-size: 28rpx;
		margin: 20rpx 0;
	}
</style>